import Vue from "vue";
import { getConfig, getAgentConfig, getRedirectUrl, doAuthorize } from "../api/wechat";

const WechatOauth2 = {};

const getURLSearchParam = (key) => {
  let params = new URLSearchParams(location.search);
  if (params.has(key)) {
    return params.get(key);
  }
  return null;
};


const hasURLSearchParam = (key) => {
  let params = new URLSearchParams(location.search);
  return params.has(key);
};


/**
 * 查询登录用户信息
 * @returns {*}
 */
const getCurrentUser = (opt) => {
  return axios({
    url: opt.baseUrl + '/current',
    method: 'get',
    params: {
      appCode: opt.appCode
    }
  });
};


/**
 * 企业微信agentConfig
 * @param baseUrl
 * @param appCode
 * @returns {*}
 */
const getWechatConfigAgent = (opt) => {
  return axios({
    url: opt.baseUrl + '/config/agent',
    method: 'get',
    params: {
      appCode: opt.appCode,
      url: location.href.split('#')[0]
    }
  });
};

const nextState = (next) => {
  let params = new URLSearchParams(location.search);
  let state = params.get("state");
  if (state && state != 'STATE') {
    try {
      let stateObj = JSON.parse(state);
      if (stateObj.path) {
        next({
          path: stateObj.path,
          query: stateObj,
          replace: true
        })
      } else {
        next();
      }
    } catch (e) {
      console.log(e);
    }
  } else {
    next();
  }
};

const initWechatConfigAgent = async (opt) => {
  if (opt.agent) {
    let resp = await getAgentConfig({ url: location.href.split('#')[0] });
    if (resp) {
      wx.invoke("agentConfig", {
        agentid: resp.agentid, // 必填，企业应用的agentid
        corpid: resp.corpid,  // 必填，企业微信的corpid
        timestamp: resp.timestamp, // 必填，生成签名的时间戳,int类型, 如 1539100800
        nonceStr: resp.nonceStr, // 必填，生成签名的随机串
        signature: resp.signature,// 必填，签名，见附录5
      }, function (res) {
        if (res.err_msg != "agentConfig:ok" && res.errMsg != "agentConfig:ok") {
          console.log("应用授权失败:" + JSON.stringify(res));
        }else{
          console.log('应用授权成功')
        }
      });
    } else {
      alert('应用授权失败');
    }
  }
};

const initWechatConfig = async (opt) => {
  let resp = await getConfig({ url: location.href.split('#')[0] });
  console.log(resp)
  if (resp) {
    wx.config({
      beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
      debug: opt.debug || false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: resp.appId, // 必填，企业微信的corpID
      timestamp: resp.timestamp, // 必填，生成签名的时间戳
      nonceStr: resp.nonceStr, // 必填，生成签名的随机串
      signature: resp.signature, // 必填，签名，见附录1
      jsApiList: opt.jsApiList || []
    });

    wx.ready(() => {
      console.log('微信初始化成功')
      Vue.prototype.$wx = wx;
      initWechatConfigAgent(opt);
    });
    wx.error(function (res) {
      console.log('微信初始化失败:' + JSON.stringify(res));
    });
  } else {
    alert('微信初始化失败');
  }
};

const setValue = (key, value) => {
  sessionStorage.setItem(key, value);
};


//键值对查找  优先级依次sessionStorage-> url?->state 对象
const getValueByKey = (key) => {
  if (sessionStorage.getItem(key)) {
    return sessionStorage.getItem(key)
  }
  if (hasURLSearchParam(key)) {
    return getURLSearchParam(key);
  }
  let stateStr = getURLSearchParam(key);
  if (stateStr != 'STATE' && stateStr != null) {
    try {
      let state = JSON.parse(stateStr)
      if (state[key]) {
        return state[key];
      }
    } catch (e) {
      console.log(`【state】无法转成json对象`, e)
    }
  }
  return null;
};

WechatOauth2.install = function (Vue, options) {
  let opt = {
    state: null,
    jsApiList: [],
    debug: false,
    agent: false
  };

  const CODE = 'code';
  const STATE = 'state';
  const TOKEN = 'token';
  const USER_INFO = 'userInfo';
  const WHITE_LIST = ['/403', '/404', '/500'];

  for (let property in options) {
    opt[property] = options[property];  // 使用 options 的配置
    setValue(property, options[property]);
    console.log(property + ':' + options[property])
  }
  Vue.$setState = (state) => {
    opt.state = state;
    setValue(STATE, state);
  };
  //路由过滤
  Vue.$permissionCheck = async function (to, from, next) {
    let token = getValueByKey(TOKEN);

    if (token || WHITE_LIST.indexOf(to.path) != -1) {
      //有登录token存在
      sessionStorage.removeItem('scanQRCode');
      initWechatConfig(opt);
      nextState(next);

    } else {
      if (hasURLSearchParam(CODE)) {
        let resp = await doAuthorize({ code: getURLSearchParam(CODE) });
        if (resp) {
          setValue(TOKEN, resp);
          initWechatConfig(opt);
          /*getCurrentUser(opt).then(response => {
            if (response.code == 200) {
              setValue(USER_INFO, JSON.stringify(response.result))
            } else {
              alert(resp.msg || resp.error);
            }
          });*/
          nextState(next);
        } else {
          alert(resp.msg || resp.error);
          next({ path: '/403' })
          return;
        }
      } else {
        //没有登录code  需要重定向oauth2地址
        let resp = await getRedirectUrl({ url: location.href.split("#")[0] });
        if (resp) {
          location.href = resp;
        } else {
          alert('服务异常');
          next({ path: '/403' })
          return;
        }
      }
    }
  };
};
export default WechatOauth2;
